import axios from "axios";
import {getToken} from "./auth";

import store from '@/store'

//创建单例
const instance = axios.create({
    baseURL: process.env.VUE_APP_BASE_URL,
    timeout: 5000 //最大相应时间
})

// 请求拦截
instance.interceptors.request.use(config => {
    if (store.getters.token) {
        // let each request carry token
        // ['X-Token'] is a custom headers key
        // please modify it according to the actual situation
        config.headers['IKness-Token'] = getToken()
    }
    return config
}, error => {
    return Promise.reject(error);
});

// 响应拦截
instance.interceptors.response.use(response => {

    const {data} = response

    if (data.code !== 20000) {
        if (data.code === 488) {
            store.dispatch('user/resetUserToken').then(() => {
                location.reload()
                // window.open('/login')
            })
            return Promise.reject(new Error(data.message || 'Error'))
        }
        return response
    }
    return response;
}, error => {
    return Promise.reject(error);
});

export default instance;
